package com.bitoon.basketdudes.web.jpa;

import java.util.*;
import javax.persistence.*;
import org.apache.log4j.Logger;

public class PersistenceManager {

    public static final boolean DEBUG = true;
    private static final PersistenceManager singleton = new PersistenceManager();
    protected HashMap<String, EntityManagerFactory> emf;

    protected EntityManagerFactory emfBasket;

    private Logger log = Logger.getLogger(PersistenceManager.class);

    public static PersistenceManager getInstance() {
        return singleton;
    }

    private PersistenceManager() {
        emf = new HashMap<String, EntityManagerFactory>();
    }

    public EntityManagerFactory getEntityManagerFactory(String db) {
        if (emf.get(db)==null) {
            createEntityManagerFactory(db);
        }

        return emf.get(db);
    }

    public void closeEntityManagerFactory(String db) {
        if (emf.get(db) != null) {
            emf.get(db).close();
            emf.remove(db);
        }
    }

    protected void createEntityManagerFactory(String db) {
        try {
            this.emf.put(db, Persistence.createEntityManagerFactory(db));
        } catch (Exception e) {
            log.error("[createEntityManagerFactory]: Error " + e, e);
        }
    }
}

